#!/bin/bash

usage() {
   [ -n "$*" ] && echo "$*"
   cat <<EOF

$me [-d int] [keyword] [keyword]...

Get stored queries descriptions from
$URL

-d int   Level of detail:
         0 - id only
         1 - title & id on single line (default)
         2 - title, id, description
         3 - title, id, description, parameters with description

Provide additional command line parameters to filter IDs by simple keywords.

Example to get all location-based land forecast alternatives with medium detail:
$me -d 2 :forecast: :point: :surface:

EOF
   exit 1
}

URL="https://opendata.fmi.fi/wfs?service=WFS&version=2.0.0&request=describeStoredQueries"
detail=1

while getopts "d:h" opt; do
  case $opt in
    d) [[ "$OPTARG" =~ [0-3] ]] || usage "Option -${opt}: invalid number $OPTARG"
       detail="$OPTARG"
    ;;
    *) usage
      ;;
  esac
done
shift $((OPTIND-1))

contains="contains(@id,':')"
if [ -n "$*" ]; then
   for i in "$@"; do
      contains="$contains and contains(@id,'$i')"
   done
fi

data="$(curl -s "$URL")"

case $detail in
0)
xmlstarlet sel -N n="http://www.opengis.net/wfs/2.0" -t -m "/n:DescribeStoredQueriesResponse/n:StoredQueryDescription[$contains]" \
-v "@id" -n <<<"$data"
;;
1)
xmlstarlet sel -N n="http://www.opengis.net/wfs/2.0" -t -m "/n:DescribeStoredQueriesResponse/n:StoredQueryDescription[$contains]" \
-v "n:Title" -o ' (' -v "@id" -o ')' -n <<<"$data"
;;
2)
xmlstarlet sel -N n="http://www.opengis.net/wfs/2.0" -t -m "/n:DescribeStoredQueriesResponse/n:StoredQueryDescription[$contains]" \
-v "n:Title" -o ' (' -v "@id" -o ')' -n -v "normalize-space(n:Abstract)" -n -n <<<"$data"
;;
3)
xmlstarlet sel -N n="http://www.opengis.net/wfs/2.0" -t -m "/n:DescribeStoredQueriesResponse/n:StoredQueryDescription[$contains]" \
-v "n:Title" -o ' (' -v "@id" -o ')' -n -v "normalize-space(n:Abstract)" -n -m "n:Parameter" -o '    ' -v "@name" -o ': ' -v "normalize-space(n:Abstract)" -n -b -n <<<"$data"
;;
esac
